import { defineStore } from "pinia";
import utils from "../utils/utils";
import moment from "moment";

interface TableColumn {
  field: string;
  title: string;
  // 经过处理后，最终得到的标题
  finalTitle: string;
  hidden: boolean;
}

interface State {
  appVersion: string;
  appUrl: string;
  appSidebar: boolean;
  appLocale: string;
  // todo 合并到 accountInfo
  accountName: string;
  accountInfo: {
    accountId: string;
    account: string;
    avatarUrl: string;
    name: string;
    gender: number;
    employeeNumber: string;
    orgCode: string;
    orgName: string;
    deptCode: string;
    deptName: string;
    roleNames: string;
  };
  //   accountInfo: any;
  accountRoles: Array<any>;
  tokenInfo: {
    expiresIn: number;
    // token 创建的时间
    createTime: string;
    token: string;
  };
  menuItems: Array<any>;
  tableColumns: Array<{
    tableName: string;
    columns: Array<TableColumn>;
  }>;
  // 临时会话状态，业务可直接使用
  // key 不存在返回 null
  session(key: string): any;
  // key 不存在返回 null
  localStorage(key: string): any;
}

// 系统状态管理对象，业务对象有个性化需求，单独创建一个模块解决
export const useStore = defineStore("useStore", {
  // 响应式状态，调用方式 store.xxx
  state: (): State => {
    // console.log("useStore.state");
    return {
      appVersion: localStorage.getItem("app-version") || "1.0.0",
      appUrl: sessionStorage.getItem("app-url") || "",
      appLocale: localStorage.getItem("app-locale") || "zh_CN",
      appSidebar: JSON.parse(localStorage.getItem("app-sidebar") || `true`),
      accountName: sessionStorage.getItem("account-name") || "",
      accountInfo: JSON.parse(
        sessionStorage.getItem("account-info") ||
          `{
                \"accountId\": \"\",
                \"account\": \"\",
                \"avatarUrl\": \"\",
                \"name\": \"\",
                \"gender\": 1,
                \"employeeNumber\": \"\",
                \"orgCode\": \"\",
                \"orgName\": \"\",
                \"deptCode\": \"\",
                \"deptName\": \"\",
                \"roleNames\": \"\"
            }`
      ),
      //   _accountInfo: null,
      accountRoles: JSON.parse(sessionStorage.getItem("account-roles") || `[]`),
      tokenInfo: JSON.parse(
        sessionStorage.getItem("token-info") ||
          `{
          \"expiresIn\": 7200, \"token\": \"createTime\", \"token\": \"\"
        }`
      ),
      menuItems: JSON.parse(sessionStorage.getItem("menu-items") || `[]`),
      tableColumns: JSON.parse(localStorage.getItem("table-columns") || `[]`),
      // key 不存在返回 null
      session: (key: string) => sessionStorage.getItem("session-" + key),
      localStorage: (key: string) => localStorage.getItem("session-" + key),
    };
  },
  // 计算属性，调用方式 store.xxx
  getters: {
    // accountInfo(state) {
    //   console.log("state._accountInfo", state._accountInfo);
    //   if (state._accountInfo == null) {
    //     state._accountInfo = JSON.parse(
    //       sessionStorage.getItem("account-info") ||
    //         `{
    //                       \"accountId\": \"\",
    //                       \"account\": \"\",
    //                       \"avatarUrl\": \"\",
    //                       \"name\": \"\",
    //                       \"gender\": 1,
    //                       \"employeeNumber\": \"\",
    //                       \"orgCode\": \"\",
    //                       \"orgName\": \"\",
    //                       \"deptCode\": \"\",
    //                       \"deptName\": \"\",
    //                       \"roleNames\": \"\"
    //                   }`
    //     );
    //   }
    //   return state._accountInfo;
    // },
  },
  // 方法，调用方式 store.xxx()
  actions: {
    setAppVersion(version: string) {
      this.appVersion = version;
      localStorage.setItem("app-version", version);
    },
    setAppUrl(appUrl: string) {
      this.appUrl = appUrl;
      sessionStorage.setItem("app-url", appUrl);
    },
    setAppLocale(locale: string) {
      this.appLocale = locale;
      localStorage.setItem("app-locale", locale);
    },
    setAppSidebar(sidebar: boolean) {
      this.appSidebar = sidebar;
      localStorage.setItem("app-sidebar", JSON.stringify(sidebar));
    },
    setAccountName(accountName: string) {
      this.accountName = accountName;
      sessionStorage.setItem("account-name", accountName);
    },
    setAccountInfo(accountInfo: any) {
      // console.log("store session accountInfo", accountInfo);
      this.accountInfo = accountInfo;
      sessionStorage.setItem("account-info", JSON.stringify(accountInfo));
    },
    setAccountRoles(roles: Array<any>) {
      if (roles == undefined) {
        // todo t
        utils.warningNotification("登录失败，当前账号未配置任何角色");
      } else {
        this.accountRoles = roles;
        sessionStorage.setItem("account-roles", JSON.stringify(roles));
      }
    },
    setTokenInfo(tokenInfo: any) {
      if (tokenInfo == undefined) {
        utils.warningNotification("登录失败，未获取有效 token");
      } else {
        tokenInfo.createTime = moment().format("YYYY-MM-DD HH:mm:ss");
        this.tokenInfo = tokenInfo;
        sessionStorage.setItem("token-info", JSON.stringify(tokenInfo));
        // console.log("SET_TOKEN_INFO", tokenInfo);
      }
    },
    setMenuItems(menuItems: Array<any>) {
      this.menuItems = menuItems;
      sessionStorage.setItem("menu-items", JSON.stringify(menuItems));
    },
    getColumns(tableName: string): Array<TableColumn> {
      // debugger;
      let exist = false;
      let columns = Array<TableColumn>();
      this.tableColumns.forEach(
        (value: { tableName: string; columns: Array<TableColumn> }) => {
          if (value.tableName == tableName) {
            exist = true;
            columns = value.columns;
            return;
          }
        }
      );
      //上面 forEach 中的 return 并没有终止，下面的 return 还会执行一次
      return columns;
    },
    setTableColumns(tableName: string, columns: Array<TableColumn>) {
      // debugger;
      let exist = false;
      this.tableColumns.forEach(
        (value: { tableName: string; columns: Array<TableColumn> }) => {
          if (value.tableName == tableName) {
            value.columns = columns;
            exist = true;
          }
        }
      );
      // console.log("SET_TABLE_COLUMN", state.tables)
      if (!exist) {
        this.tableColumns.push({ tableName: tableName, columns: columns });
      }
      localStorage.setItem("table-columns", JSON.stringify(this.tableColumns));
    },
    setSession(key: string, value: any) {
      if (value == undefined) {
        console.log("store session undefined value，key=", key);
      }
      sessionStorage.setItem("session-" + key, value);
    },
    removeSession(key: string) {
      sessionStorage.removeItem(key);
    },
    clearSession() {
      // 注销
      this.accountName = "";
      // 不能设置为 null，因为下级属性被其他对象使用，上级对象为 null，即 null.xxx 会引发异常；设置为 {} 会触发响应事件
      this.accountInfo = {};
      sessionStorage.removeItem("account-name");
      sessionStorage.removeItem("account-info");
      sessionStorage.removeItem("account-roles");
      sessionStorage.removeItem("token-info");
      sessionStorage.removeItem("menu-items");
    },
    setLocalStorage(key: string, value: any) {
      if (value == undefined) {
        console.log("store session undefined value，key=", key);
      }
      localStorage.setItem("session-" + key, value);
    },
    removeLocalStorage(key: string) {
      localStorage.removeItem("session-" + key);
    },
  },
});
